package com.yh.hljapp.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.github.jjobes.slidedatetimepicker.SlideDateTimeListener;
import com.github.jjobes.slidedatetimepicker.SlideDateTimePicker;
import com.google.gson.Gson;
import com.yh.hljapp.AppConfig;
import com.yh.hljapp.AppContext;
import com.yh.hljapp.R;
import com.yh.hljapp.api.ErrorHandler;
import com.yh.hljapp.api.RetrofitSingleton;
import com.yh.hljapp.base.BaseFragment;
import com.yh.hljapp.common.FullyLinearLayoutManager;
import com.yh.hljapp.common.MyScrollview;
import com.yh.hljapp.common.PLog;
import com.yh.hljapp.common.StringUtils;
import com.yh.hljapp.common.TDevice;
import com.yh.hljapp.common.Time;
import com.yh.hljapp.common.UIHelper;
import com.yh.hljapp.gddb.gbmanager.AddSale_Manager;
import com.yh.hljapp.gddb.gdbean.AddSaleInt_HeadBean;
import com.yh.hljapp.gddb.gdbean.AddSaleInt_bodyBean;
import com.yh.hljapp.gddb.gdbean.AddSaleInt_body_InOutList_Bean;
import com.yh.hljapp.gddb.gdbean.Add_Sync_Bean;
import com.yh.hljapp.gddb.gdbean.Add_body_Bean;
import com.yh.hljapp.modules.adatper.Add_Sale_Adapter;
import com.yh.hljapp.modules.bean.AddSaleInt_HB_Bean;
import com.yh.hljapp.modules.bean.CM;
import com.yh.hljapp.modules.bean.CustPhone;
import com.yh.hljapp.modules.bean.CustPhoneHGZ;
import com.yh.hljapp.modules.bean.Result;
import com.yh.hljapp.modules.bean.SimpleBackPage;
import com.yh.hljapp.modules.bean.User;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static android.content.Context.MODE_PRIVATE;
import static com.yh.hljapp.AppConfig.SCN_CUST_ACTION_SCODE;
import static com.yh.hljapp.R.id.imageView;
import static com.yh.hljapp.R.id.linearLayout;
import static com.yh.hljapp.R.id.textView;

/**
 * =========================
 * 版权所有，违法必究
 * 作者：zhanghang
 * <p>
 * 工程：hlj
 * <p>
 * 文件名：ADDSaleIntFragment
 * <p>
 * 创建时间：2017.07.31.11:40
 */

public class ADDSaleIntFragment extends BaseFragment implements Add_Sale_Adapter.OnSaleAddAdapterListern {

    @InjectView(R.id.tv_date)
    TextView tvDate;
    @InjectView(R.id.tv_all)
    TextView tv_all;
    @InjectView(R.id.ll_date)
    LinearLayout llDate;
    @InjectView(R.id.tv_jh_unit)
    TextView tvJhUnit;
    @InjectView(R.id.ll_jh_unit)
    LinearLayout llJhUnit;
    @InjectView(R.id.ll_content)
    LinearLayout ll_content;
    @InjectView(R.id.tv_bz)
    TextView tvBz;
    @InjectView(R.id.ll_bz)
    LinearLayout llBz;
    @InjectView(R.id.tv_ys)
    TextView tvYs;
    @InjectView(R.id.tv_modle)
    TextView tv_modle;
    @InjectView(R.id.ll_ys)
    LinearLayout llYs;
    @InjectView(R.id.tv_bg)
    TextView tvBg;
    @InjectView(R.id.ll_bg)
    LinearLayout llBg;
    @InjectView(R.id.tv_sh_warehouse)
    TextView tvShWarehouse;
    @InjectView(R.id.ll_sh_warehouse)
    LinearLayout llShWarehouse;
    @InjectView(R.id.recyclerview)
    RecyclerView mRecycleview;
    @InjectView(R.id.scrollView)
    MyScrollview scrollView;
    private String currBillNumb;
    private Add_Sale_Adapter mAdapter;
    ArrayList<Add_body_Bean> checkedCKS;
    private AddSaleInt_HeadBean addSaleInt_HeadBean;
    private int position;
    private boolean isSave;
    private String mType;
    private User mUser;
    private int count;
//    private List<String> mFbillNumberList = new ArrayList<>();

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    Observer<List<CustPhoneHGZ>> observers = new Observer<List<CustPhoneHGZ>>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            String errBody = ErrorHandler.handle(e);
            Snackbar.make(getActivity().getWindow().getDecorView(), errBody, Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(List<CustPhoneHGZ> custPhoneHGZs) {
            if (custPhoneHGZs.size() == 0) {
                handleOtherText(mFBase, mFWeight);
            } else {
                for (int i = 0; i < custPhoneHGZs.size(); i++) {
                    String number = custPhoneHGZs.get(i).getNumber();
                    if (currBillNumb.equals(number)) {
                        Snackbar.make(getActivity().getWindow().getDecorView(), "该产品已经入库了,请确认！", Snackbar.LENGTH_SHORT).show();
                        return;
                    }
                }
            }
        }
    };
    private String mFWeight;
    private String mFBase;
    private BroadcastReceiver mSamDataReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(SCN_CUST_ACTION_SCODE)) {
                String message = intent.getStringExtra(AppConfig.SCN_CUST_EX_SCODE);
                JSONObject jo = null;
                try {
                    jo = new JSONObject(message);
                    mFBase = jo.optString("FBase");
                    mFWeight = jo.optString("FWeight");
                    String fBillNumber = jo.optString("FBillNumber");
                    currBillNumb = fBillNumber;
//                    mFbillNumberList.add(fBillNumber);
                    showWaitDialog();
                    RetrofitSingleton.getApiService(mActivity).
                            OrgCodesAll(fBillNumber, 1, 1000000)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(observers);

                    User currentUser = AppContext.getInstance().getCurrentUser();
                    if (currentUser == null) {
                        Snackbar.make(mActivity.getWindow().getDecorView(), "当前用户为空，请重新登陆", Snackbar.LENGTH_SHORT).show();
                    } else {

                    }
                } catch (JSONException e) {
                    Snackbar.make(mActivity.getWindow().getDecorView(), "请扫描正确二维码!", Snackbar.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }
        }
    };
    private List<AddSaleInt_body_InOutList_Bean> mBodyInOuts;
    private String mModel;


    private void handleOtherText(String text, String fWeight) {
        //先去判断扫描的单号是否存在
        boolean matExist = AddSale_Manager.getInstance(mActivity).isMatExist(text);
        if (matExist) {//存在
            onlyMatInsert(text, fWeight);
        } else {//不存在
            Snackbar.make(mActivity.getWindow().getDecorView(), "出库单不匹配，请重新扫描或同步数据！", Snackbar.LENGTH_SHORT).show();
        }
    }


    //扫描条码只对应一个物料时的添加流程
    private void onlyMatInsert(String barcode, String fWeight) {
        //先判断已添加的中是否存在
        List<Add_body_Bean> listMatBean = mAdapter.getBackList();
        for (int i = 0; i < listMatBean.size(); i++) {
            Add_body_Bean addSyncBean = listMatBean.get(i);
            String id = addSyncBean.getFBillNum();
            mModel = addSyncBean.getModel();
            //判断是否添加一样
            if (currBillNumb.equals(id)) {
                Snackbar.make(mActivity.getWindow().getDecorView(), "请确认该产品是否已经添加！", Snackbar.LENGTH_SHORT).show();
                return;
            }
        }
        //设置数据
        Add_Sync_Bean matById = AddSale_Manager.getInstance(mActivity).getMatById(barcode);
        String model = matById.getModel();


        Add_body_Bean addSyncBean = new Add_body_Bean();

        addSyncBean.setUnit_id(matById.getUnit_id());
        addSyncBean.setId(matById.getId());
        addSyncBean.setCount(fWeight);
        addSyncBean.setModel(model);
        addSyncBean.setName(matById.getName());
        addSyncBean.setNumber(matById.getNumber());
        addSyncBean.setUnitgroup_name(matById.getUnitgroup_name());
        addSyncBean.setUnit_name(matById.getUnit_name());
        addSyncBean.setDefunitId(matById.getDefunitId());
        addSyncBean.setBaseName(matById.getBaseName());
        addSyncBean.setBaseunit(matById.getBaseunit());
        addSyncBean.setUnitgroup_id(matById.getUnitgroup_id());
        addSyncBean.setFDCStockName(addSaleInt_HeadBean.getFStockName());
        addSyncBean.setFDCStockID(addSaleInt_HeadBean.getFStock());
        addSyncBean.setFBillNum(currBillNumb);

//        BackMatManager.getInstance(mActivity).insertBackMat(backMatBean);//缓存
        checkedCKS.add(addSyncBean);
        count += Integer.parseInt(fWeight);
        tv_all.setText("" + count);

        TextView mTextView = new TextView(mActivity);
        mTextView.setTextSize(25);
        mTextView.setTextColor(Color.BLACK);
        mTextView.setGravity(Gravity.CENTER_HORIZONTAL);
        int childCount = ll_content.getChildCount();
        boolean haseSame = false;
        int pos = -1;
        if (childCount == 0) {
            mTextView.setText(model + " 重量:" + fWeight);
            ll_content.addView(mTextView);
        } else {
            for (int i = 0; i < childCount; i++) {
                String s = ((TextView) ll_content.getChildAt(i)).getText().toString();
                if (s.contains(model)) {
//                ll_content.addView(mTextView);
                    pos = i;
                    haseSame = true;
                    break;
//                    ((TextView) ll_content.getChildAt(i)).setText(model + " zzz:" + fWeight);
                } else {
//                    mTextView.setText(model + " www:" + fWeight);
//                    ll_content.addView(mTextView);
                }
            }
            if (haseSame) {
                String text = ((TextView) ll_content.getChildAt(pos)).getText().toString();
                String substring = text.substring(text.indexOf(":") + 1, text.length());
                int i = Integer.parseInt(substring);
                int i1 = Integer.parseInt(fWeight);

                ((TextView) ll_content.getChildAt(pos)).setText(model + " 重量:" + (i + i1));
            } else {
                mTextView.setText(model + " 重量:" + fWeight);
                ll_content.addView(mTextView);
            }
        }

        mAdapter = new Add_Sale_Adapter(mActivity, checkedCKS, this);
        mRecycleview.setAdapter(mAdapter);

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(mActivity, R.layout.fragment_sale_int, null);
        ButterKnife.inject(this, view);
        initView(view);
        initData();
        return view;
    }

    @Override
    public void initView(View view) {
        super.initView(view);
        TDevice.hideSoftKeyboard(mActivity);
        setHasOptionsMenu(true);
        IntentFilter intentFilter = new IntentFilter(SCN_CUST_ACTION_SCODE);
        mActivity.registerReceiver(mSamDataReceiver, intentFilter);
        isSave = false;
        llJhUnit.setOnClickListener(this);
        llBz.setOnClickListener(this);
        llBg.setOnClickListener(this);
        llYs.setOnClickListener(this);
        llShWarehouse.setOnClickListener(this);
        llDate.setOnClickListener(this);
        checkedCKS = new ArrayList<>();

        FullyLinearLayoutManager linearLayoutManager = new FullyLinearLayoutManager(getContext());
        mRecycleview.setNestedScrollingEnabled(false);
        //设置布局管理器
        mRecycleview.setLayoutManager(linearLayoutManager);

        mAdapter = new Add_Sale_Adapter(mActivity, checkedCKS, this);
    }

    @Override
    public void initData() {
        super.initData();
        mUser = AppContext.getInstance().getCurrentUser();
        String nowYMDHMSTime = Time.getNowYMDHMSTime();
        tvDate.setText(nowYMDHMSTime);
        addSaleInt_HeadBean = new AddSaleInt_HeadBean();
        addSaleInt_HeadBean.setDate(nowYMDHMSTime);
        //text
        String tvJhUnits = AppContext.getInstance().getProperty("tvJhUnit");
        String tvBzs = AppContext.getInstance().getProperty("tvBz");
        String tvBgs = AppContext.getInstance().getProperty("tvBg");
        String tvYss = AppContext.getInstance().getProperty("tvYs");
        String tvShWarehouses = AppContext.getInstance().getProperty("tvShWarehouse");

        //id
        String tvJhUnits_id = AppContext.getInstance().getProperty("tvJhUnit_id");
        String tvBzs_id = AppContext.getInstance().getProperty("tvBz_id");
        String tvBgs_id = AppContext.getInstance().getProperty("tvBg_id");
        String tvYss_id = AppContext.getInstance().getProperty("tvYs_id");
        String tvShWarehouses_id = AppContext.getInstance().getProperty("tvShWarehouse_id");

        if (!StringUtils.isEmpty(tvJhUnits) && !StringUtils.isEmpty(tvBzs) && !StringUtils.isEmpty(tvBgs)
                && !StringUtils.isEmpty(tvYss) && !StringUtils.isEmpty(tvShWarehouses)) {
            tvJhUnit.setText(tvJhUnits);
            tvBz.setText(tvBzs);
            tvBg.setText(tvBgs);
            tvYs.setText(tvYss);
            tvShWarehouse.setText(tvShWarehouses);

            addSaleInt_HeadBean.setFDeptId(tvJhUnits_id);
            addSaleInt_HeadBean.setFDeptName(tvJhUnits);

            addSaleInt_HeadBean.setFBan(tvBzs_id);
            addSaleInt_HeadBean.setFBanName(tvBzs);

            addSaleInt_HeadBean.setFBUser(tvBgs_id);
            addSaleInt_HeadBean.setFBUserName(tvBgs);

            addSaleInt_HeadBean.setFYUser(tvYss_id);
            addSaleInt_HeadBean.setFYUserName(tvYss);

            addSaleInt_HeadBean.setFStock(tvShWarehouses_id);
            addSaleInt_HeadBean.setFStockName(tvShWarehouses);
        }

        Bundle bundle = getArguments();
        mType = bundle.getString("TYPE");
        if ("show".equals(mType)) {

            String headid = bundle.getString("ID");
            long Id = Long.parseLong(headid);
            String count = AppContext.getInstance().getProperty(headid);
            tv_all.setText(count);

            List<String> environmentList = new ArrayList<String>();
            SharedPreferences preferDataList = mActivity.getSharedPreferences(headid, MODE_PRIVATE);
            int environNums = preferDataList.getInt("Environ", 0);
            for (int i = 0; i < environNums; i++) {
                String environItem = preferDataList.getString("item_" + i, null);
                environmentList.add(environItem);
            }

            for (int i = 0; i < environmentList.size(); i++) {
                TextView mTextView = new TextView(mActivity);
                mTextView.setTextSize(25);
                mTextView.setTextColor(Color.BLACK);
                mTextView.setGravity(Gravity.CENTER_HORIZONTAL);
                mTextView.setText(environmentList.get(i).toString());
                ll_content.addView(mTextView,i);
            }

            addSaleInt_HeadBean = AddSale_Manager.getInstance(mActivity).getHeadById(Id + "");
            if (addSaleInt_HeadBean != null) {
                tvDate.setText(addSaleInt_HeadBean.getDate());
                String fDeptName = addSaleInt_HeadBean.getFDeptName();
                if (fDeptName != null) {
                    tvJhUnit.setText(addSaleInt_HeadBean.getFDeptName());
                } else {
                    tvJhUnit.setText(tvJhUnits);
                }
                String fBanName = addSaleInt_HeadBean.getFBanName();
                if (fBanName != null) {
                    tvBz.setText(addSaleInt_HeadBean.getFBanName());
                } else {
                    tvBz.setText(tvBzs);
                }
                String fyUserName = addSaleInt_HeadBean.getFYUserName();
                if (fyUserName != null) {
                    tvYs.setText(addSaleInt_HeadBean.getFYUserName());
                } else {
                    tvYs.setText(tvYss);
                }
                String fbUserName = addSaleInt_HeadBean.getFBUserName();
                if (fbUserName != null) {
                    tvBg.setText(addSaleInt_HeadBean.getFBUserName());
                } else {
                    tvBg.setText(tvBgs);
                }
                String fStockName = addSaleInt_HeadBean.getFStockName();
                if (fStockName != null) {
                    tvShWarehouse.setText(addSaleInt_HeadBean.getFStockName());
                } else {
                    tvShWarehouse.setText(tvShWarehouses);
                }

            }
            List<Add_body_Bean> backMatsByHeadId = AddSale_Manager.getInstance(mActivity).getBackMatsByHeadId(Id);
            checkedCKS.addAll(backMatsByHeadId);

            mAdapter = new Add_Sale_Adapter(mActivity, checkedCKS, this);
            mRecycleview.setAdapter(mAdapter);
        } else {
            mAdapter = new Add_Sale_Adapter(mActivity, checkedCKS, this);

        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Bundle bundle = new Bundle();
        switch (v.getId()) {
            case R.id.ll_jh_unit:
                bundle.putString("type", "jhdw");
                UIHelper.showSimpleBackForResult(this, mActivity, 1, SimpleBackPage.CUST_PHEON, bundle, "交货单位");
                break;
            case R.id.ll_bz:
                bundle.putString("type", "bz");
                UIHelper.showSimpleBackForResult(this, mActivity, 2, SimpleBackPage.CUST_PHEON, bundle, "班组");
                break;
            case R.id.ll_bg:
                bundle.putString("type", "bg");
                UIHelper.showSimpleBackForResult(this, mActivity, 3, SimpleBackPage.CUST_PHEON, bundle, "保管");
                break;
            case R.id.ll_ys:
                bundle.putString("type", "ys");
                UIHelper.showSimpleBackForResult(this, mActivity, 4, SimpleBackPage.CUST_PHEON, bundle, "验收");
                break;
            case R.id.ll_sh_warehouse:
                bundle.putString("type", "shck");
                UIHelper.showSimpleBackForResult(this, mActivity, 5, SimpleBackPage.CUST_PHEON, bundle, "收货仓库");
                break;
            case R.id.ll_date:
                new SlideDateTimePicker.Builder(getFragmentManager())
                        .setListener(listener)
                        .setInitialDate(new Date())
                        .build()
                        .show();
                break;
        }
    }

    private SlideDateTimeListener listener = new SlideDateTimeListener() {

        @Override
        public void onDateTimeSet(Date date) {
            String str = StringUtils.getDateString(date);
            tvDate.setText(str);
            addSaleInt_HeadBean.setDate(str);
        }

        @Override
        public void onDateTimeCancel() {
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            final CustPhone item = (CustPhone) data.getSerializableExtra("item");
            if (item != null) {
                String name = item.getName();
                String id = item.getId();
                switch (requestCode) {
                    case 1:
                        tvJhUnit.setText(name);
                        addSaleInt_HeadBean.setFDeptId(id);
                        addSaleInt_HeadBean.setFDeptName(name);
                        AppContext.getInstance().setProperty("tvJhUnit", name);
                        AppContext.getInstance().setProperty("tvJhUnit_id", id);
                        break;
                    case 2:
                        tvBz.setText(name);
                        addSaleInt_HeadBean.setFBan(id);
                        addSaleInt_HeadBean.setFBanName(name);
                        AppContext.getInstance().setProperty("tvBz", name);
                        AppContext.getInstance().setProperty("tvBz_id", id);
                        break;
                    case 3:
                        tvBg.setText(name);
                        addSaleInt_HeadBean.setFBUser(id);
                        addSaleInt_HeadBean.setFBUserName(name);
                        AppContext.getInstance().setProperty("tvBg", name);
                        AppContext.getInstance().setProperty("tvBg_id", id);
                        break;
                    case 4:
                        tvYs.setText(name);
                        addSaleInt_HeadBean.setFYUser(id);
                        addSaleInt_HeadBean.setFYUserName(name);
                        AppContext.getInstance().setProperty("tvYs", name);
                        AppContext.getInstance().setProperty("tvYs_id", id);
                        break;
                    case 5:
                        tvShWarehouse.setText(name);
                        addSaleInt_HeadBean.setFStock(id);
                        addSaleInt_HeadBean.setFStockName(name);
                        AppContext.getInstance().setProperty("tvShWarehouse", name);
                        AppContext.getInstance().setProperty("tvShWarehouse_id", id);
                        break;
                    case 7://adapter中点击发货仓库 自选的仓库
                        ArrayList<Add_body_Bean> backList = mAdapter.getBackList();
                        Add_body_Bean addSyncBean = backList.get(position);
                        addSyncBean.setTDCStockID(item.getId());
                        addSyncBean.setTDCStockName(item.getName());
                        backList.set(position, addSyncBean);
                        mAdapter.setBackList(backList);
                        mAdapter.notifyItemChanged(position);
                        break;
                }
            }
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_add_mat, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.send_btn:
                subMat();
                break;
            case R.id.btn_save:
                saveMat();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    //提交
    private void subMat() {
        List<String> environmentList = new ArrayList<String>();
//        SharedPreferences preferDataList = mActivity.getSharedPreferences("EnvironDataList", MODE_PRIVATE);
//        int environNums = preferDataList.getInt("EnvironNums", 0);
//        for (int i = 0; i < environNums; i++) {
//            String environItem = preferDataList.getString("item_" + i, null);
//            environmentList.add(environItem);
//        }

        ArrayList<Add_body_Bean> addSyncBeen_List = mAdapter.getBackList();
        if (addSyncBeen_List == null || addSyncBeen_List.size() == 0) {
            Snackbar.make(mActivity.getWindow().getDecorView(), "请扫描物料，再提交", Snackbar.LENGTH_SHORT).show();
            return;
        }
        for (int i = 0; i < addSyncBeen_List.size(); i++) {
            environmentList.add(addSyncBeen_List.get(i).getFBillNum());
        }
        //表头
        String date = addSaleInt_HeadBean.getDate();
        String mFDeptId = addSaleInt_HeadBean.getFDeptId();
        String mFStock = addSaleInt_HeadBean.getFStock();
        String fyUser = addSaleInt_HeadBean.getFYUser();
        String mFbUser = addSaleInt_HeadBean.getFBUser();
        String mFBan = addSaleInt_HeadBean.getFBan();

        if (mUser != null) {
            String id = mUser.getId();
            addSaleInt_HeadBean.setFUser(id);
        } else {
            Snackbar.make(mActivity.getWindow().getDecorView(), "当前用户获取失败，请重新登陆！", Snackbar.LENGTH_SHORT).show();
        }

        if (!StringUtils.isEmpty(mFDeptId) && !StringUtils.isEmpty(mFStock) && !StringUtils.isEmpty(mFbUser)) {

            addSaleInt_HeadBean.setDate(date);
            addSaleInt_HeadBean.setFDeptId(mFDeptId);
            addSaleInt_HeadBean.setFStock(mFStock);
            addSaleInt_HeadBean.setFYUser(fyUser);
            addSaleInt_HeadBean.setFBUser(mFbUser);
            addSaleInt_HeadBean.setFBan(mFBan);

            //表体
            List<AddSaleInt_bodyBean> bodys = new ArrayList<>();

            mBodyInOuts = new ArrayList<>();
            //判断是不是列表进来的
//            if ("show".equals(mType)) {
            if (environmentList != null && environmentList.size() > 0) {
                for (int i = 0; i < environmentList.size(); i++) {
                    AddSaleInt_body_InOutList_Bean bodyInOutsBean = new AddSaleInt_body_InOutList_Bean();
                    bodyInOutsBean.setFText(environmentList.get(i));
                    mBodyInOuts.add(bodyInOutsBean);
                }
            }
//            } else {
//                for (int i = 0; i < mFbillNumberList.size(); i++) {
//                    AddSaleInt_body_InOutList_Bean bodyInOutsBean = new AddSaleInt_body_InOutList_Bean();
//                    bodyInOutsBean.setFText(mFbillNumberList.get(i));
//                    mBodyInOuts.add(bodyInOutsBean);
//                }
//            }

            for (int i = 0; i < addSyncBeen_List.size(); i++) {
                AddSaleInt_bodyBean bodyBean = new AddSaleInt_bodyBean();

                Add_body_Bean addSyncBeans = addSyncBeen_List.get(i);

                String fCount = addSyncBeans.getCount();
                if (fCount.contains(".")) {
                    String counts = fCount.substring(0, fCount.indexOf("."));
                    bodyBean.setFQty(counts);
                } else {
                    bodyBean.setFQty(fCount);
                }
                String unit_id = addSyncBeans.getUnit_id();
                String fdcStockID = addSyncBeans.getTDCStockID();  //表体id
                String id = addSyncBeans.getId();

                if (!StringUtils.isEmpty(fdcStockID)) {
                    bodyBean.setFStockId(fdcStockID);
                } else if (!StringUtils.isEmpty(mFStock)) {
                    bodyBean.setFStockId(mFStock);
                } else {
                    bodyBean.setFStockId("0");
                }

                bodyBean.setFUnitId(unit_id);
                bodyBean.setFProductID(id);

                bodys.add(bodyBean);
            }

            showWaitDialog();
            AddSaleInt_HB_Bean addSaleIntHbBean = new AddSaleInt_HB_Bean();
            addSaleIntHbBean.setBodyList(bodys);
            addSaleIntHbBean.setInoutList(mBodyInOuts);
            addSaleIntHbBean.setHeadDetail(addSaleInt_HeadBean);

            Gson gson = new Gson();
            String json = gson.toJson(addSaleIntHbBean);
            String token = AppContext.getInstance().getProperty(AppConfig.PRIVATE_TOKEN);
            CM cm = new CM();
            cm.setToken(token);
            cm.setData(json);
            RetrofitSingleton.getApiService(mActivity).
                    InStockBillSubmit(cm)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);
        } else {
            Snackbar.make(mActivity.getWindow().getDecorView(), "必填信息不能为空！", Snackbar.LENGTH_SHORT).show();
        }
    }

    //保存
    private void saveMat() {

        ArrayList<Add_body_Bean> addSyncBeen_List = mAdapter.getBackList();
        int countList = 0;
        if (addSyncBeen_List != null && addSyncBeen_List.size() > 0) {
            for (int i = 0; i < addSyncBeen_List.size(); i++) {
                countList += Integer.parseInt(addSyncBeen_List.get(i).getCount());
            }

            User currentUser = AppContext.getInstance().getCurrentUser();
            if (currentUser != null) {
                addSaleInt_HeadBean.setUsername(currentUser.getName());

                AddSale_Manager.getInstance(mActivity).inOrRe(addSaleInt_HeadBean);
                AddSaleInt_HeadBean lastHead = AddSale_Manager.getInstance(mActivity).getLastHead();
                for (int i = 0; i < addSyncBeen_List.size(); i++) {
                    addSyncBeen_List.get(i).setHead(lastHead);
                }
                long headId = addSyncBeen_List.get(0).getHeadId();
                AppContext.getInstance().setProperty("" + headId, "" + countList);
                AddSale_Manager.getInstance(mActivity).insertBackMats(addSyncBeen_List);

                List<String> environmentList = new ArrayList<String>();
                int childCount = ll_content.getChildCount();
                for (int i = 0; i < childCount; i++) {
                    String s = ((TextView) ll_content.getChildAt(i)).getText().toString();
                    environmentList.add(s);
                }

                SharedPreferences.Editor editor = mActivity.getSharedPreferences(""+headId, MODE_PRIVATE).edit();
                editor.putInt("Environ", environmentList.size());
                for (int i = 0; i < environmentList.size(); i++) {
                    editor.putString("item_" + i, environmentList.get(i));
                }
                editor.commit();


//            SharedPreferences.Editor editor = mActivity.getSharedPreferences("EnvironDataList", MODE_PRIVATE).edit();
//            editor.putInt("EnvironNums", mFbillNumberList.size());
//            for (int i = 0; i < mFbillNumberList.size(); i++) {
//                editor.putString("item_" + i, mFbillNumberList.get(i));
//            }
//            editor.commit();

                Snackbar.make(mActivity.getWindow().getDecorView(), "保存成功!", Snackbar.LENGTH_SHORT).show();
                Intent intent = new Intent(AppConfig.SALE_Int_SAVE);
                mActivity.sendBroadcast(intent);

                isSave = true;
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mActivity.finish();
                        Bundle bundle = new Bundle();
                        UIHelper.showSimpleBack(mActivity, SimpleBackPage.ADD_SALE_INT, bundle, "产品入库");
                    }
                }, 1000);//3秒后执行Runnable中的run方法

            } else {
                Snackbar.make(mActivity.getWindow().getDecorView(), "当前用户获取失败，请重新登陆!", Snackbar.LENGTH_SHORT).show();
            }
        } else {
            Snackbar.make(mActivity.getWindow().getDecorView(), "未扫描单据不能保存!", Snackbar.LENGTH_SHORT).show();
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            mActivity.unregisterReceiver(mSamDataReceiver);
        } catch (Exception ex) {
        }
        ButterKnife.reset(this);
    }

    @Override
    public void onFHCKClick(Add_body_Bean bean, int position) {
        this.position = position;
        Bundle bundle = new Bundle();
        bundle.putString("type", "shck");
        UIHelper.showSimpleBackForResult(this, mActivity, 7, SimpleBackPage.CUST_PHEON, bundle, "收货仓库");
    }

    @Override
    public void onDeleted(Add_body_Bean bean,int position) {
        count -= Integer.parseInt(bean.getCount());
        tv_all.setText("" + count);


        int childCount = ll_content.getChildCount();
        if (childCount >0) {
            for (int i = 0; i < childCount; i++) {
                String s = ((TextView) ll_content.getChildAt(i)).getText().toString();
                if (s.contains(bean.getModel())) {

                    String text = ((TextView) ll_content.getChildAt(i)).getText().toString();
                    String substring = text.substring(text.indexOf(":") + 1, text.length());
                    int a = Integer.parseInt(substring);
                    int i1 = Integer.parseInt(bean.getCount());
                    if ((a-i1)==0){
                        ll_content.removeViewAt(i);
                    }else{
                        ((TextView) ll_content.getChildAt(i)).setText(bean.getModel() + " 重量:" + (a - i1));
                    }
                    break;
                }
            }
        }
    }

    Observer<Result> observer = new Observer<Result>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            String errBody = ErrorHandler.handle(e);
            Snackbar.make(getActivity().getWindow().getDecorView(), errBody, Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(Result result) {
            hideWaitDialog();
            if (result.isSuccess()) {

                Snackbar.make(mActivity.getWindow().getDecorView(), "提交成功!", Snackbar.LENGTH_SHORT).show();
                if ("show".equals(mType) || isSave) {
                    AddSale_Manager.getInstance(mActivity).delAllById(addSaleInt_HeadBean.getId());
                    AddSale_Manager.getInstance(mActivity).delAllByHeadId(addSaleInt_HeadBean.getId());//提交成功后删除缓存
                    mActivity.finish();
                }
                mActivity.finish();
            } else {
                Snackbar.make(mActivity.getWindow().getDecorView(), result.getMessage(), Snackbar.LENGTH_SHORT).show();
            }
        }
    };
}

